//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    message,
    Divider,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import EbookArticlePhotosCreateForm from './EbookArticlePhotosCreateForm'; //新增表单
import EbookArticlePhotosUpdateForm from './EbookArticlePhotosUpdateForm'; //修改表单
import EbookArticlePhotosViewForm  from './EbookArticlePhotosViewForm'; //查看表单

import styles from './EbookArticlePhotosList.less';
import {getValue} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { Option } = Select;



/* eslint react/no-multi-comp:0 */
@connect(({ ebookarticlephotos, loading }) => ({
    ebookarticlephotos,
    loading: loading.models.ebookarticlephotos,
}))

@Form.create()
class EbookArticlePhotosList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
    };

    columns = [
		{
	        title: '图片存储位置',
	        dataIndex: 'type_store',
	        key: 'type_store',
        },        {
	        title: '图片原图',
	        dataIndex: 'goods_image',
	        key: 'goods_image',
        },       {
	        title: '图片显示终端',
	        dataIndex: 'images_client',
	        key: 'images_client',
        },       {
	        title: '默认主题',
	        dataIndex: 'is_default',
	        key: 'is_default',
        },		{
    title: '操作',
    render: (text, record) => (
		<Fragment>
			<a onClick={() => this.handleViewModalVisible(true, record)}>查看</a>
			<Divider type="vertical" />
		    <a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
		    <Divider type="vertical" />
		    <a onClick={() => this.handleDeleteRecord(record)}>删除</a>
	    </Fragment>
	),
},
];


componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
    	type: 'ebookarticlephotos/query_page_for_ebookarticlephotos',
    });
}



handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
    newObj[key] = getValue(filtersArg[key]);
    return newObj;
}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'ebookarticlephotos/query_page_for_ebookarticlephotos',
        payload: params,
    });
};

previewItem = id => {
    router.push(`/profile/basic/${id}`);
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
    });
    dispatch({
        type: 'ebookarticlephotos/query_page_for_ebookarticlephotos',
        payload: {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};

handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) return;
    switch (e.key) {
        case 'batchremove':
            dispatch({
                type: 'ebookarticlephotos/delete_by_primarykey_for_ebookarticlephotos',
                payload: {
                    id: selectedRows.map(row => row.id),
    			},
			    callback: () => {
			        this.setState({
			            selectedRows: [],
			        });
			    },
    		});
        break;
    	case 'batchsend':
	        dispatch({
	            type: 'ebookarticlephotos/delete_by_primarykey_for_ebookarticlephotos',
	            payload: {
	                id: selectedRows.map(row => row.id),
	    		},
		        callback: () => {
		            this.setState({
		                selectedRows: [],
		            });
		        },
	    	});
        break;

    default:
        break;
    }
};

handleSelectRows = rows => {
    this.setState({
        selectedRows: rows,
    });
};

handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

    const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
    };

    this.setState({
        formValues: values,
    });

    dispatch({
        type: 'ebookarticlephotos/query_page_for_ebookarticlephotos',
        payload: values,
    });
});
};

handleModalVisible = flag => {
    this.setState({
        modalVisible: !!flag,
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
        type: 'ebookarticlephotos/insert_for_ebookarticlephotos',
        payload: {
            id: fields.id,
            article_id: fields.article_id,
            images_client: fields.images_client,
            images_type: fields.images_type,
            type_store: fields.type_store,
            goods_commonid: fields.goods_commonid,
            color_id: fields.color_id,
            goods_image: fields.goods_image,
            goods_image_samll: fields.goods_image_samll,
            goods_image_sort: fields.goods_image_sort,
            is_default: fields.is_default,
        },
    });

    message.success('添加成功');
    this.handleModalVisible();

};


handleDeleteRecord = record => {
        const { dispatch } = this.props;

        dispatch({
	        type: 'ebookarticlephotos/delete_by_primarykey_for_ebookarticlephotos',
	        payload: {
	        	recordid: record.id,
	        },
	        callback: () => {
		        this.setState({
		        	selectedRows: [],
		        });
	        },
        });

        message.success('删除成功');


};

handleUpdate = fields => {

    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
        type: 'ebookarticlephotos/update_for_ebookarticlephotos',
        payload: {
                id: fields.id,
                article_id: fields.article_id,
                images_client: fields.images_client,
                images_type: fields.images_type,
                type_store: fields.type_store,
                goods_commonid: fields.goods_commonid,
                color_id: fields.color_id,
                goods_image: fields.goods_image,
                goods_image_samll: fields.goods_image_samll,
                goods_image_sort: fields.goods_image_sort,
                is_default: fields.is_default,
        },
    });

    message.success('修改成功');
    this.handleUpdateModalVisible();

};

renderSimpleForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
	        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			    <Col md={8} sm={24}>
			        <FormItem label="图片存储位置">
			        	{getFieldDecorator('type_store')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
			    <Col md={8} sm={24}>
			        <FormItem label="图片原图">
			        	{getFieldDecorator('goods_image')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
				        <Button type="primary" htmlType="submit">
				       		查询
				        </Button>
				        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
				        	重置
				        </Button>
				        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
				        	展开 <Icon type="down" />
				        </a>
			        </span>
		        </Col>
	        </Row>
        </Form>
	);
}

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
	        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
			        <FormItem label="图片存储位置">
			        	{getFieldDecorator('type_store')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
			    
			    <Col md={8} sm={24}>
			        <FormItem label="图片原图">
				        {getFieldDecorator('goods_image')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
			    
				<Col md={8} sm={24}>
			        <FormItem label="图片显示终端">
				        {getFieldDecorator('images_client')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
			    
			    <Col md={8} sm={24}>
					<FormItem label="默认主题">
				        {getFieldDecorator('is_default')(
				            <Select placeholder="请选择" style={{ width: '100%' }}>
				                <Option value="0">否</Option>
				                <Option value="1">是</Option>
				            </Select>
				        )}
					</FormItem>
			    </Col>
	    	</Row>
		    <div style={{ overflow: 'hidden' }}>
				<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
		        		查询
		        	</Button>
		        	<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
		        		重置
		        	</Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        收起 <Icon type="up" />
			        </a>
		        </div>
	        </div>
        </Form>
);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            ebookarticlephotos: { data },
            loading,
        } = this.props;



        const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues  } = this.state;
        const menu = (
            <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
            <Menu.Item key="batchremove">批量删除</Menu.Item>
            <Menu.Item key="batchsend">批量上报</Menu.Item>
            </Menu>
    	);

        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
        };
        
        const updateMethods = {
            handleUpdateModalVisible: this.handleUpdateModalVisible,
            handleUpdate: this.handleUpdate,
        };
        
        const viewMethods = {
            handleViewModalVisible: this.handleViewModalVisible
        };
        
        return (
            <PageHeaderWrapper title="文章相册信息列表">
            <Card bordered={false}>
            <div className={styles.ebookArticlePhotostableList}>
            <div className={styles.ebookArticlePhotostableListForm}>{this.renderForm()}</div>
            <div className={styles.ebookArticlePhotostableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
        新增
        </Button>
        <Divider type="vertical" />
            {selectedRows.length > 0 && (
                    <span>
                    <Button>批量导出</Button>
                    <Divider type="vertical" />
                <Dropdown overlay={menu}>
                <Button>
                更多操作 <Icon type="down" />
                </Button>
                </Dropdown>
                </span>
    )}
    </div>
        <StandardTable
        rowKey={"id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>

        <EbookArticlePhotosCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <EbookArticlePhotosUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <EbookArticlePhotosViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
    }
}

export default EbookArticlePhotosList;
